package com.mydemo.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

public class ReadWordToMd {

    /**
     * 统一处理 DOC 和 DOCX 文件并转换为 Markdown
     */
    public static void convertWordToMarkdown(String wordFilePath, String markdownFilePath) throws IOException {
        String content = readWordFile(wordFilePath);
        String markdownContent = convertToMarkdown(content);

        try (FileWriter writer = new FileWriter(markdownFilePath)) {
            writer.write(markdownContent);
        }
    }

    /**
     * 读取 Word 文件内容
     */
    private static String readWordFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();

        if (filePath.toLowerCase().endsWith(".docx")) {
            content.append(readDocxFile(filePath));
        } else if (filePath.toLowerCase().endsWith(".doc")) {
            content.append(readDocFile(filePath));
        } else {
            throw new IllegalArgumentException("不支持的文件格式: " + filePath);
        }

        return content.toString();
    }

    /**
     * 读取 DOCX 文件
     */
    private static String readDocxFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            // 读取段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                content.append(paragraph.getText()).append("\n");
            }

            // 读取表格
            for (XWPFTable table : document.getTables()) {
                content.append(processTable(table)).append("\n");
            }
        }

        return content.toString();
    }

    /**
     * 读取 DOC 文件
     */
    private static String readDocFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();

        try (FileInputStream fis = new FileInputStream(filePath);
             HWPFDocument document = new HWPFDocument(fis)) {

            WordExtractor extractor = new WordExtractor(document);
            String[] paragraphs = extractor.getParagraphText();

            for (String paragraph : paragraphs) {
                content.append(paragraph).append("\n");
            }
        }

        return content.toString();
    }

    /**
     * 处理表格内容转换为 Markdown 格式
     */
    private static String processTable(XWPFTable table) {
        StringBuilder tableMarkdown = new StringBuilder();
        tableMarkdown.append("\n");

        // 处理表头
        if (table.getRows().size() > 0) {
            XWPFTableRow headerRow = table.getRow(0);
            tableMarkdown.append("|");
            for (XWPFTableCell cell : headerRow.getTableCells()) {
                tableMarkdown.append(" ").append(cell.getText()).append(" |");
            }
            tableMarkdown.append("\n");

            // 添加分隔行
            tableMarkdown.append("|");
            for (int i = 0; i < headerRow.getTableCells().size(); i++) {
                tableMarkdown.append(" --- |");
            }
            tableMarkdown.append("\n");

            // 处理数据行
            for (int i = 1; i < table.getRows().size(); i++) {
                XWPFTableRow row = table.getRow(i);
                tableMarkdown.append("|");
                for (XWPFTableCell cell : row.getTableCells()) {
                    tableMarkdown.append(" ").append(cell.getText()).append(" |");
                }
                tableMarkdown.append("\n");
            }
        }

        return tableMarkdown.toString();
    }

    /**
     * 将文本内容转换为 Markdown 格式
     */
    private static String convertToMarkdown(String text) {
        StringBuilder markdown = new StringBuilder();
        markdown.append("# 文档内容\n\n");

        String[] paragraphs = text.split("\n");
        boolean inCodeBlock = false;

        for (String paragraph : paragraphs) {
            paragraph = paragraph.trim();

            if (paragraph.isEmpty()) {
                if (!inCodeBlock) {
                    markdown.append("\n");
                }
                continue;
            }

            // 简单的格式识别和转换
            if (isLikelyHeading(paragraph)) {
                markdown.append("\n## ").append(paragraph).append("\n\n");
            } else if (paragraph.startsWith("- ") || paragraph.startsWith("* ")) {
                // 列表项
                markdown.append(paragraph).append("\n");
            } else if (paragraph.matches("^\\d+\\.\\s.*")) {
                // 数字列表
                markdown.append(paragraph).append("\n");
            } else {
                // 普通段落
                markdown.append(paragraph).append("\n\n");
            }
        }

        return markdown.toString();
    }

    /**
     * 判断是否可能是标题
     */
    private static boolean isLikelyHeading(String text) {
        return text.length() < 50 &&
                (text.endsWith(":") ||
                        text.matches("[A-Z][^.]*") ||
                        text.matches(".*[\\u4e00-\\u9fa5]{2,}.*")); // 匹配中文标题
    }

    // 使用示例
    public static void main(String[] args) {
        try {
            convertWordToMarkdown("C:\\Users\\Administrator\\Desktop\\文件\\中华人民共和国民法典.docx", "C:\\Users\\Administrator\\Desktop\\文件\\output.md");
            System.out.println("转换完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

